package hw1.package1.space;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.app.AlertDialog;
import android.os.Bundle;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.*;

 
public class Homework1Activity extends ListActivity{
	

    CitiesAdapter adapter;
    Button addC, exit;
    ImageView img;
    private final static String CityList="citylist.txt";
 
    @Override
    public void onCreate (Bundle savedInstanceBundle) {
    	super.onCreate (savedInstanceBundle); 

        adapter = new CitiesAdapter (this);
        setContentView (R.layout.main);
        setListAdapter (adapter);
        addC=(Button)findViewById(R.id.bAdd);
        exit=(Button)findViewById(R.id.bExit);

        addC.setOnClickListener(new View.OnClickListener() {  //when the user presses the button AddCity 
			
			public void onClick(View v) {
				Intent intent=new Intent();
				intent.setClass(Homework1Activity.this, AddCity.class);  
				startActivityForResult(intent, 0);  //start another activity, AddCity, with request code 0
				
			}
		});
        
        exit.setOnClickListener(new View.OnClickListener() {  //when the user presses the button Exit
			
			public void onClick(View v) {
				AlertDialog.Builder builder = new AlertDialog.Builder(Homework1Activity.this);  //build an alert dialog which asks for his confirmation 
				builder.setMessage("Are you sure you want to exit?")
				       .setCancelable(false)
				       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) { //if the users chooses to continue the action finish the activity
				                Homework1Activity.this.finish();
				           }
				       })
				       .setNegativeButton("No", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {      //else return
				                dialog.cancel();
				           }
				       });
				AlertDialog alert = builder.create();
			
				alert.show ();        //display the dialog
				
			}
		});
        
        	
        	try {       //when the activity starts, take the list of cities and add them into the CityAdapter                        
    	    	InputStream in = openFileInput(CityList);
    	    	if (in != null) {
    		    	InputStreamReader tmp = new InputStreamReader(in);
    		    	BufferedReader reader = new BufferedReader(tmp);
    		    	String str;
     
    		    	while ((str = reader.readLine()) != null) {
    		    		adapter.addCity(str);
    		    	}
    		    	in.close();
     
    		    	
    	    	}
        	} catch (java.io.FileNotFoundException e) {
        		// that's OK, we probably haven't created it yet
        	} catch (Throwable t) {
        	Toast.makeText(this, "Exception: " + t.toString(), 2000).show();
        	}
      

        getListView().setOnItemLongClickListener(new OnItemLongClickListener() { //when the user long clicks on a list item remove it from the list
 
			public boolean onItemLongClick(AdapterView<?> listAdapter, View view, int position, long id) {
                                City c = (City)adapter.getItem (position);
                                adapter.removeCity(c);           
				return true;
			}
		});

    }
    
    public void onResume(){      //on resume take the list of cities and add them into the CityAdapter 
    	super.onResume(); 
    	if (adapter==null){
    	
        	try {
    	    	InputStream in = openFileInput(CityList);
    	    	if (in != null) {
    		    	InputStreamReader tmp = new InputStreamReader(in);
    		    	BufferedReader reader = new BufferedReader(tmp);
    		    	String str;
     
    		    	while ((str = reader.readLine()) != null) {
    		    		adapter.addCity(str);
    		    	}
    		    	in.close();
     
    		    	
    	    	}
        	} catch (java.io.FileNotFoundException e) {
        		// that's OK, we probably haven't created it yet
        	} catch (Throwable t) {
        	Toast.makeText(this, "Exception: " + t.toString(), 2000).show();
        	}
        }
   		
    	}
    
    public void onPause(){ //on pause save the list of cities into "citylist.txt"
    	super.onPause();

    	try {
    		
	    	OutputStreamWriter out = new OutputStreamWriter(openFileOutput(CityList, 0));
	    	BufferedWriter bw = new BufferedWriter(out);
	    	for (int i=0;i<adapter.getCount();i++){
				bw.write(adapter.getItem(i).toString());
				if(i!=adapter.getCount()-1)
				bw.newLine();
	    	}
			bw.close();
    	} catch (Throwable t) {
    	Toast.makeText(this, "Exception: " + t.toString(), 2000).show();
    	}
    }
    
 
    public void onStop(){ //on stop save the list of cities into "citylist.txt"
    	super.onStop();

    	try {
	    	OutputStreamWriter out = new OutputStreamWriter(openFileOutput(CityList, 0));
	    	BufferedWriter bw = new BufferedWriter(out);
	    	for (int i=0;i<adapter.getCount();i++){
	    		bw.write(adapter.getItem(i).toString());
	    		if(i!=adapter.getCount()-1)
			    bw.newLine();}
			bw.close();
    	} catch (Throwable t) {
    	Toast.makeText(this, "Exception: " + t.toString(), 2000).show();
    	}
    
    }
    
    public void onActivityResult (int requestCode, int resultCode, Intent data){  //get the data (i.e. the name of the city the user wants to add to the list)
    	if(requestCode==0)                                                       //with the help of the intent started earlier, with request code 0
    		if(resultCode==1){                                                   //if the result code is 1
    			adapter.addCity(data.getStringExtra("nume"));          
    	
    	}
    }
    @Override
    public void onListItemClick (ListView list, View v, int position, long id)    //when the user clicks on a city start the CityWeather activity
    {
        City c = (City)adapter.getItem (position);
        Intent intent=new Intent(this,CityWeather.class);
		intent.setAction("Show Info");
		intent.putExtra("cname", c.nume);                //also deliver the name of the city the user has clicked
		startActivityForResult(intent,1);               //and set the request code to 1
    }
} 
